import notFoundImg from '@/assets/images/nocourse.png'
import { OrderConfirm } from '@/types/orderConfirm/index'
import { Toast } from 'antd-mobile'
import React, { FC, useEffect, useState } from 'react'
import PayAttention from './payAttention'
import OrderCoupon from '../coupon/orderCoupon'
import { useAppSelector, useAppDispatch } from '@/store'
import {
  setStartPayTime,
  setPayParam,
  setPayPrice,
  selectPayTimeSpan,
  selectPayParam,
} from '@/store/payCenter'
import { selectCurrendStdAdd } from '@/store/address'
import PerpaidCardIndex from './prepaidCard'
import { useNavigate } from 'react-router-dom'
import { EPaySimpleCode } from '@/types/payCenter'
import { addTradeUrl } from '@/api/orderConfirm'
import confirm from '@/components/home/confirm'
import { decode } from 'js-base64'
import { getQueryVariable } from '@/utils/http'
import qs from 'qs'
import { XBusinesslineId } from '@/constants'
import {
  couponChangePrice,
  confirmUpdatePrice,
  updateOrderCoupon,
  selectCardUpdatePriceInfo,
} from '@/store/confirmPay'
import { useAsyncEffect } from 'ahooks'
import { ordercouponlist } from '@/api/orderCoupon'
import { OrderCouponInfo } from '@/types/orderCoupon'
interface PaymentParam {
  paymentData: OrderConfirm
}
const empty: FC<PaymentParam> = (props) => {
  const [agree, setAgree] = useState(!!props.paymentData.constractInfo?.isDefault)

  const agreestyleStr = 'text-red-E02727 icon-icon_selected'
  /**当前地址更新 */
  const navigate = useNavigate()
  const dispatch = useAppDispatch()
  const currendStdAdd = useAppSelector(selectCurrendStdAdd)
  const payTimeSpan = useAppSelector(selectPayTimeSpan)
  const payParam = useAppSelector(selectPayParam)
  /**商城传入 */
  const idEncode = getQueryVariable('idEncode') as string
  let idEncodeObj: any = {}
  let courseId = ''
  if (idEncode) {
    idEncodeObj = eval(`(${decode(idEncode)})`)
    if (idEncodeObj && idEncodeObj.productIds && idEncodeObj.productIds.split('-').length > 1)
      courseId = idEncodeObj.productIds.split('-')[1]
  }
  /**更新价格 */
  const cardUpdatePriceInfo = useAppSelector(selectCardUpdatePriceInfo)
  /**优惠券列表 */
  /** 确定提交订单*/
  const payFn = () => {
    //to do  添加支付参数，添加支付时间
    dispatch(
      setPayPrice(
        cardUpdatePriceInfo.realPayMoney?.toString() || props.paymentData.realPayMoney.toString(),
      ),
    )
    dispatch(setStartPayTime(Date.now()))
    dispatch(
      setPayParam({
        payCode: EPaySimpleCode.WEIXIN,
        isUseBalance: props.paymentData.balance,
        orderNum: '',
      }),
    )
    setTimeout(() => {
      const param = {
        idEncode: idEncode,
        isUseBalance: props.paymentData.balance,
        orderType: props.paymentData.orderType,
        addId: currendStdAdd?.id,
        stuCouponId: 'JTVCJTVE',
        grouponId: 0,
        grouponOrderNum: 0,
        stuCardIds: '',
        'X-Businessline-Id': XBusinesslineId,
        app_blid: 30,
      }
      window.location.href = `${addTradeUrl}?${qs.stringify(param)}`
    }, 50)
  }
  const submit = () => {
    if (
      (agree && !props.paymentData.isSend) ||
      (agree && currendStdAdd?.id && !!props.paymentData.isSend)
    ) {
      /**判断是否有支付 */
      if (payTimeSpan > 0 && payParam.orderNum != '') {
        confirm(
          <span className=" text-r1.4 text-gray-333333 text-left ">
            检测到你有待支付订单，请先支付。支付后重新购买此课程，可享多科优惠。
          </span>,
          () => {
            navigate(
              `/payStatus?X-Businessline-Id=${XBusinesslineId}&orderNum=${payParam.orderNum}`,
            )
          },
          () => {
            payFn()
          },
          '查看支付订单',
          '取消',
        )
      } else {
        payFn()
      }
    } else {
      Toast.show({
        content: '请阅读并同意合同协议',
      })
    }
  }
  /** 礼品卡*/
  const prepaidCardInfo = props.paymentData.prepaidCardInfo
    ? props.paymentData.prepaidCardInfo
    : null
  /**优惠券 */
  useAsyncEffect(async () => {
    const res = await ordercouponlist({
      app_id: 1,
      product_info: props.paymentData.couponProdInfo.map((val) => ({
        product_id: val.id,
        price: val.price,
      })),
      best_price: props.paymentData.realPayMoney,
      'X-Businessline-Id': XBusinesslineId,
    })
    dispatch(updateOrderCoupon(res.result.data))

    // setOrderCouponInfo(res.data)
  }, [])
  return (
    <>
      <div className=" p-r1.2  pt-r2.0 h-r18.8 w-auto  bg-white  shadow-bs5 m-r1.2 rounded-r0.8">
        <div className=" w-full clear-both  text-gray-333333 text-r1.4 font-normal ">
          <span className=" float-left ">商品金额</span>
          <span className=" float-right font-semibold  font-SFProDisplay">
            {props.paymentData.payPrice}
          </span>
        </div>
        <OrderCoupon
          course_id={courseId}
          paymentData={props.paymentData}
          balance={props.paymentData.balance}
          couponInfo={props.paymentData.couponInfo}
          productInfo={props.paymentData.productInfo}
        ></OrderCoupon>
        <PerpaidCardIndex
          balance={props.paymentData.balance}
          productInfo={props.paymentData.productInfo}
          course_id={courseId}
          prepaidCardInfo={prepaidCardInfo ? prepaidCardInfo : {}}
        ></PerpaidCardIndex>
        <div className=" clear-both  border border-white-F3F3F4  scale-y-50 mt-r1.3 mb-r1.3 "></div>
        <div className=" clear-both overflow-hidden relative ">
          <span className=" float-right font-regular text-gray-333333 text-r1.5 font-normal">
            合计：
            <span className=" text-gray-333333 text-r2.0  font-SFProDisplay">
              {cardUpdatePriceInfo.realPayPrice || props.paymentData.realPayPrice}
            </span>
          </span>
        </div>
      </div>
      <div className='h-auto w-auto  m-r1.2 "'>
        <PayAttention agreementDescription={props.paymentData.agreementDescription}></PayAttention>
        <div className="font-normal font-regular">
          <span
            className=" inline-block w-r1.5 relative  "
            onClick={() => {
              setAgree(!agree)
            }}
          >
            <i
              className={
                'inline-block iconfont text-r1.2 ' +
                (agree ? agreestyleStr : ' icon-icon_unselected  text-gray-878E9A ')
              }
            ></i>
          </span>
          <span className=" inline-block m-r0.2 text-gray-999999">
            {props.paymentData.constractInfo?.constractDesc}
          </span>
          <a
            className=" inline-block text-red-E02727"
            target={'_blank'}
            href={props.paymentData.constractInfo?.constractLink}
            rel="noreferrer"
          >
            {props.paymentData.constractInfo?.constractBtn}
          </a>
        </div>
      </div>

      <div className="w-full fixed bottom-0  h-r5.6  bg-white">
        <div className=" h-r6.0 pl-r1.6 pr-r1.6 pt-r0.9 pb-r1.0 leading-r6.0 overflow-hidden">
          <span className=" text-r1.2  float-left leading-r4.0  font-normal ">
            实付金额：
            <span className=" text-red-FF3627 font-semibold text-r2.0 leading-r4.0  ">
              {cardUpdatePriceInfo.realPayPrice || props.paymentData.realPayPrice}
            </span>
          </span>{' '}
          <span
            className=" float-right right-5 text-r1.4 h-r4.0 w-r17.0  text-white leading-r4.0 rounded-r2.0  bg-gradient-to-r from-orange-FF664F to-orange-FF3627  inline-block text-center "
            onClick={() => {
              submit()
            }}
          >
            立即支付
          </span>
        </div>
      </div>
    </>
  )
}

export default empty
